﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JoyxyAnalyzer.Utils
{
    public class HexHelper
    {
        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static List<string> byteToHexString(List<byte> bytes)
        {
            List<string> hex = new List<string>();
            if (bytes != null)
            {
                foreach (byte b in bytes)
                {
                    hex.Add(b.ToString("X2"));
                }
            }

            return hex;
        }

        /// <summary>
        /// 十六进制转十进制
        /// </summary>
        /// <param name="hexs"></param>
        /// <returns></returns>
        public static List<string> hexToDecs(List<string> hexs)
        {
            List<string> decs = new List<string>();
            if (hexs != null)
            {
                foreach (string hex in hexs)
                {
                    decs.Add(Convert.ToInt32(hex, 16).ToString());
                }
            }

            return decs;
        }

        /// <summary>
        /// 十六进制转十进制
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static int hexToDec(string hex)
        {
            return Convert.ToInt32(hex, 16);
        }

        /// <summary>
        /// 字符串转十六进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string str2Hex(string s)
        {
            string result = string.Empty;

            byte[] arrByte = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(s);
            for (int i = 0; i < arrByte.Length; i++)
            {
                result += System.Convert.ToString(arrByte[i], 16).ToUpper() + " ";        //Convert.ToString(byte, 16)把byte转化成十六进制string 
            }

            return result;
        }

        /// <summary>
        /// 16进制转换成字符串
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string hexToString(List<string> hexs)
        {
            string sHex = "";
            foreach (string hex in hexs)
            {
                sHex += ((char)short.Parse(hex, global::System.Globalization.NumberStyles.HexNumber)).ToString();
            }

            return sHex;
        }

        /// <summary>
        /// 16进制转换成字符串
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string hexToString(string hex)
        {
            return ((char)short.Parse(hex, global::System.Globalization.NumberStyles.HexNumber)).ToString();
        }
    }
}
